﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using DHJ.Cost.CostBooking;
using DHJ.Cost.CostBooking.Config;
using DHJ.Cost.CostRecord.Dto;
using DHJ.Cost.Tasks;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace DHJ.Cost.CostRecord
{
    public class CostRecordAppService : CostAppServiceBase, ICostRecordAppService
    {
        private readonly IRepository<ActualCost, Guid> _actualCostRepository;
        private readonly IBatchManager _batchManager;

        public CostRecordAppService(IRepository<ActualCost, Guid> actualCostRepository, IBatchManager batchManager)
        {
            _actualCostRepository = actualCostRepository;
            _batchManager = batchManager;
        }


        public async Task<PagedResultDto<YclCostListDto>> GetYclReCords(GetCostRecordsInput input)
        {
            var query = _actualCostRepository.GetAll().OfType<DirectCost>()
                .Where(e => e.Detail.Category == "原材料成本")
                .Where(e => e.Workshop.HasValue && e.Workshop == Workshops.Workshop.Sheet)
                .WhereIf(!input.Filter.IsNullOrWhiteSpace(), e =>
                        e.ExtensionData.Contains(input.Filter) ||
                        e.Batches.Value.Contains(input.Filter));

            var count = await query.CountAsync();

            var list = await query
                .OrderBy(input.Sorting)
                .PageBy(input)
                .ToListAsync();

            var dtos = ObjectMapper.Map<List<YclCostListDto>>(list);

            var batchIds = dtos.Select(e => e.Batches.Identifiers).SelectMany(e => e).Select(e => e.BatchId).ToList();

            var batches = await _batchManager.Batches().Include(e => e.Task).Where(e => batchIds.Contains(e.Id)).ToListAsync();

            foreach (var dto in dtos)
            {
                var obj = JsonConvert.DeserializeObject<JObject>(dto.ExtensionData);

                dto.Extend = obj["原材料成本_Extend"]?.ToObject<原材料成本_Extend>();

                var batchId = dto.Batches.Identifiers.FirstOrDefault()?.BatchId;

                if (batchId.IsNullOrWhiteSpace())
                    continue;

                var batch = batches.FirstOrDefault(e => e.Id == batchId);

                if (batch != null)
                {
                    dto.TaskNum = batch.Task?.TaskNum;
                    dto.ProductId = batch.Task?.ProductId;
                    dto.ProductName = batch.Task?.ProductName;
                }
            }

            return new PagedResultDto<YclCostListDto>(count, dtos);
        }
    }
}
